import 'package:chatgreat/bloc/creative_island_bloc.dart';
import 'package:chatgreat/helper/ability.dart';
import 'package:chatgreat/helper/color.dart';
import 'package:chatgreat/helper/my_widget.dart';
import 'package:chatgreat/lang/lang.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/sliver_component.dart';
import 'package:chatgreat/page/creative_island/draw/components/creative_item.dart';
import 'package:chatgreat/page/component/theme/custom_size.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';

import '../../../helper/event.dart';

class DrawListScreen extends StatefulWidget {
  final SettingRepository setting;
  const DrawListScreen({super.key, required this.setting});

  @override
  State<DrawListScreen> createState() => _DrawListScreenState();
}

class _DrawListScreenState extends State<DrawListScreen> {
  @override
  void initState() {
    context
        .read<CreativeIslandBloc>()
        .add(CreativeIslandItemsV2LoadEvent(forceRefresh: false));

    GlobalEvent().on("refresh_1", (data) {
      if (mounted) {
        context
            .read<CreativeIslandBloc>()
            .add(CreativeIslandItemsV2LoadEvent(forceRefresh: false));
      }
    });
    super.initState();

    // PaintingBinding.instance.imageCache.maximumSizeBytes = 1024 *1024 *300;
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final customColors = Theme.of(context).extension<CustomColors>()!;
    return BackgroundContainer(
      setting: widget.setting,
      child: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('images/bg1.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          body: _buildIslandItems(customColors),
        ),
      ),
    );
  }

  /// 创作列表
  Widget _buildIslandItems(
    CustomColors customColors,
  ) {
    return SliverCreateComponent(
      title: const Text(
        '创作',
        style: TextStyle(
          fontSize: CustomSize.appBarTitleSize,
          color: Colors.white,
        ),
      ),
      child: SafeArea(
        child: BlocBuilder<CreativeIslandBloc, CreativeIslandState>(
          buildWhen: (previous, current) =>
          current is CreativeIslandItemsWorkLoaded,
          builder: (context, state) {
            if (state is CreativeIslandItemsWorkLoaded) {
              List<Widget> widgets = [];
              for (var element in state.items) {
                widgets.add(SliverToBoxAdapter(
                  child: Padding(
                    padding: const EdgeInsets.only(left: 12, top: 6),
                    child: MyTextWeight(
                      element.name,
                      17,
                      Colors.white,
                      FontWeight.w500,
                    ),
                  ),
                ));
                widgets.add(SliverPadding(
                  padding: const EdgeInsets.only(top: 10, left: 12, right: 12, bottom: 18),
                  sliver: SliverGrid.builder(
                      addAutomaticKeepAlives: false,
                      addRepaintBoundaries: false,
                      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        childAspectRatio: 1.7,
                        mainAxisSpacing: 10,
                        crossAxisSpacing: 10,
                      ),
                      itemCount: element.works.length,
                      itemBuilder: (BuildContext context, int index) {
                        final e = element.works[index];
                        return CreativeItem(
                          iconImageURL: e.icon ?? '',
                          imageURL: e.cover ?? '',
                          name: e.name,
                          title: e.title,
                          titleColor: Colors.white,
                          tag: '',
                          size: 'other',
                          onTap: () {
                            context.push('/creative-draw/docreate',
                                extra: e);
                          },
                        );
                      }),
                ));
              }

              return CustomScrollView(
                slivers: [
                  ...widgets
                ],
              );
            }
            return Center(
              child: CircularProgressIndicator(
                  color: customColors.themeBlueColor),
            );
          },
        ),
      ),
    );
  }

  int _calCrossAxisCount(BuildContext context) {
    var width = MediaQuery.of(context).size.width;
    if (width > CustomSize.maxWindowSize) {
      width = CustomSize.maxWindowSize;
    }

    return (width / 400).round() > 2 ? 2 : (width / 400).round();
  }
}
